//
// Created by 78472 on 2022/5/11.
//

#include "param.h"
#include "common/httpUtil.h"
#include "log/Logging.h"
#include <algorithm>
#include "accessPublishUtil.h"
#include "serviceRequestHandler.h"
#include "sceneFileUpdate.h"
#include "siteService/service_site_manager.h"

using namespace servicesite;

void setOkResponse(Response& response){
    qlibc::QData data;
    data.setInt("code", 0);
    data.setString("error", "ok");
    data.putData("response", qlibc::QData().setBool("register", true));
    response.set_content(data.toJsonString(), "text/json");
}

void setErrorResponse(Response& response){
    qlibc::QData data;
    data.setInt("code", 0);
    data.setString("error", "error");
    data.putData("response", qlibc::QData().setBool("register", false));
    response.set_content(data.toJsonString(), "text/json");
}

void setCommonOkResponse(Response& response, qlibc::QData responseData = qlibc::QData()){
    qlibc::QData data;
    data.setInt("code", 0);
    data.setString("error", "ok");
    data.putData("response", responseData);
    response.set_content(data.toJsonString(), "text/json");
}

void setCommonErrorResponse(Response& response, string errMessage = "error", qlibc::QData responseData = qlibc::QData()){
    qlibc::QData data;
    data.setInt("code", -1);
    data.setString("error", errMessage);
    data.putData("response", responseData);
    response.set_content(data.toJsonString(), "text/json");
}


//获取面板信息
int getPanelInfo_service_request_handler(const Request& request, Response& response){
    LOG_INFO << "==>getPanelInfo_service_request_handler: " << qlibc::QData(request.body).toJsonString();
    setCommonOkResponse(response, configParamUtil::getInstance()->getPanelInfo());
    return 0;
}

//设置面板信息
int setPanelInfo_service_request_handler(const Request& request, Response& response){
    qlibc::QData requestData(request.body);
    LOG_INFO << "==>setPanelInfo_service_request_handler: " << requestData.toJsonString();
    qlibc::QData panelConfigData = requestData.getData("request");
    qlibc::QData oldPanelConfigData = configParamUtil::getInstance()->getPanelInfo();

    if(panelConfigData.toJsonString() != oldPanelConfigData.toJsonString()){
        //存储配置信息
        configParamUtil::getInstance()->setPanelInfo(panelConfigData);
        
        //发布面板配置信息改变
        qlibc::QData publishData;
        publishData.setString("message_id", PANELINFO_MODIFIED_MESSAGE_ID);
        publishData.putData("content", panelConfigData);
        ServiceSiteManager::getInstance()->publishMessage(PANELINFO_MODIFIED_MESSAGE_ID, publishData.toJsonString());
        LOG_BLUE << "publish: " << publishData.toJsonString();
    }

    setCommonOkResponse(response);
    return 0;
}


/**
 * 收到面板注册消息后，从虹美站点获取decode值，然后将面板注册到云端
 */
int hongmeiPanelRegister_service_request_handler(const Request& request, Response& response){
    qlibc::QData requestData(request.body);
    LOG_INFO << "==>hongmeiPanelRegister_service_request_handler: " << requestData.toJsonString();
   
    //判断device_sn字段是否为空，如果不为空，则请求虹美站点获取decode，存储decode值，然后将面板注册到云端
    qlibc::QData panelConfigData = configParamUtil::getInstance()->getPanelInfo();
    string device_sn = panelConfigData.getString("device_sn");
    string app_type = panelConfigData.getString("app_type");
    string dcode;

    if(!device_sn.empty() && app_type == "hongmei"){
        qlibc::QData response_hm;
        if(access_service_hongmei_getDcode("127.0.0.1", qlibc::QData().setString("mac", panelConfigData.getString("device_mac")), response_hm)){ 
            dcode = response_hm.getData("response").getString("dcode");
            bool isConnected = response_hm.getData("response").getBool("g_connected");
            if(!isConnected){
                setErrorResponse(response);
                return 0;
            }
        }else{
            LOG_RED << "get decode request failed .....";
            setErrorResponse(response);
            return 0;
        }

        //组装请求体
        qlibc::QData registerDevice, registerData;
        registerDevice.setString("sn", panelConfigData.getString("device_sn"));
        registerDevice.setString("mac", panelConfigData.getString("device_mac"));
        registerDevice.setString("hwver", panelConfigData.getString("hwver"));
        registerDevice.setString("swver", panelConfigData.getString("swver"));
        registerDevice.setString("dcode", dcode);
        registerData.putData("device", registerDevice);

        //发送请求
        qlibc::QData responseBody;
        if(access_service_hongmeiCloud(getCloudAddress(), PanelRegister2CloudUrl, registerData, responseBody)){
            LOG_BLUE << "response body: " << responseBody.toJsonString();
            string code = responseBody.getString("code");
            if(code == "1000" || code == "3001"){
                setOkResponse(response);
            }else{
                setErrorResponse(response);
            }   
        }else{
            setErrorResponse(response);
        }

    }else{
        setErrorResponse(response);
    }

    return 0;
}


void hongmeiGatewayInfo_messageHandle(const Request &request)
{
    qlibc::QData data(request.body);
    LOG_INFO << "hongmeiGatewayInfo_messageHandle: " << data.toJsonString();
    
    // 新下发属性消息
    qlibc::QData gatewayInfo = data.getData("content").getData("payload").getData("gatewayInfo");
    string mac = gatewayInfo.getString("mac");
    string cid = gatewayInfo.getString("cid");
    string familyId = gatewayInfo.getString("familyId");
    string phone = gatewayInfo.getString("phone");
    string roomName = gatewayInfo.getString("roomName");
    string roomId = gatewayInfo.getString("roomId");
    qlibc::QData location;
    location.setString("room_name", roomName);
    location.setString("room_no", roomId);

    // 旧属性消息
    qlibc::QData panelInfo = configParamUtil::getInstance()->getPanelInfo();
    string device_mac = panelInfo.getString("device_mac");
    
    bool panelInfoChange = false;
    if(mac == device_mac){
        if(panelInfo.getString("cid") != cid){
            panelInfo.setString("cid", cid);
            panelInfoChange = true;
        }
        if(panelInfo.getString("familyId") != familyId){
            panelInfo.setString("familyId", familyId);
            panelInfoChange = true;
        }
        if(panelInfo.getString("phone") != phone){
            panelInfo.setString("phone", phone);
            panelInfoChange = true;
        }
        if(!roomName.empty() || !roomId.empty()){
            panelInfo.putData("location", location);
        }
    }

    // 如果面板消息发生变化，发布变化消息
    if(panelInfoChange){
        publish_message_config_self_info_update(panelInfo);
    }
}
